package com.ydm.myapp001.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import com.ydm.myapp001.R;
import com.ydm.myapp001.bean.OneGoodsCategory;

import java.util.List;

public class GoodsCategoryAdapter  extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Callback mCallback;
    private Context mContext;
    private List<OneGoodsCategory> listItems;

    public GoodsCategoryAdapter(Context mContext, List<OneGoodsCategory> listItems, Callback callback) {
        this.mContext = mContext;
        this.listItems = listItems;
        this.mCallback = callback;
    }

    /**
     * 自定义接口，用于回调Item点击事件到Activity
     */
    public interface Callback {
        public void onGoodsCategoryItemClick(View view, int position);
    }


    /**
     * 用于创建ViewHolder实例的，并把加载出来的布局传入到构造函数当中，最后将viewholder的实例返回
     *
     * @param parent
     * @param viewType
     * @return
     */
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // 不需要检查是否复用，因为只要进入此方法，必然没有复用
        // 因为RecyclerView 通过Holder检查复用
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_goods_category,
                parent, false);
        return new GoodsCategoryViewHolder(view, mCallback);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        OneGoodsCategory bean = listItems.get(position);
        GoodsCategoryViewHolder viewHolder = (GoodsCategoryViewHolder) holder;
        viewHolder.tv_name.setText(bean.getName());
    }

    @Override
    public int getItemCount() {
        return listItems.size();
    }


    class GoodsCategoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        TextView tv_name;
        private Callback mListener;

        public GoodsCategoryViewHolder(View itemView, Callback callback) {
            super(itemView);
            //将全局的监听赋值给接口
            this.mListener = callback;
            itemView.setOnClickListener(this);
            tv_name = itemView.findViewById(R.id.tv_category_name);
        }

        /**
         * 实现OnClickListener接口重写的方法
         *
         * @param v
         */
        @Override
        public void onClick(View v) {
            if (mListener != null) {
                mListener.onGoodsCategoryItemClick(v, getAdapterPosition());//getLayoutPosition())两个方法都可以
            }
        }
    }
}
